#include "apue.h"
#include <sys/stat.h>
#include <stdio.h>

int main() {
    size_t pathlen, triple_len, nexLen;
    char *dirpath, *tmpt;
    char *pre;
    int i;
    char name[100];

    tmpt= path_alloc(&pathlen);
    triple_len= 10 * pathlen;
    if ((dirpath= realloc(tmpt, triple_len)) == NULL)
        err_sys("realloc failed");
    if (dirpath != tmpt)
        free(tmpt);

    pre= "practice_4_16_test_dir_";
    for (i=1; i<1800; ++i) {
        if (getcwd(dirpath, triple_len) < 0)
            err_sys("getcwd failed");
        else
            printf("cwd: %s\n", dirpath);

        if(sprintf(name, "%s%03d", pre, i) < 0)
            err_sys("sprintf name failed\n");

        nexLen= strlen(dirpath) + strlen(name) + 2; // 2 is '/' + '\0'

        if (nexLen > triple_len) {
            err_ret("path over than three times maximum length, end\n");
            break;
        }
        if (nexLen > pathlen) {
            printf("path over than the maximum length.\n");
        }

        // printf("current dir path: %s\n", dirpath);

        if (mkdir(name, DIR_MODE) < 0) {
            err_ret("mkdir failed");
            break;
        }
        
        chdir(name);
    }

    free(dirpath);
    return(0);
}
